/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package avl.sv.shared.XML;

import avl.sv.shared.Annotations.Annotation;
import avl.sv.shared.Annotations.Attributes;
import avl.sv.shared.Annotations.ROI;
import avl.sv.shared.Annotations.ROIOval;
import avl.sv.shared.Annotations.ROIPoly;
import avl.sv.shared.Annotations.ROIRectangle;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 *
 * @author benbryan
 */
public class AnnotationsXML_Parser {
                 
    public ArrayList<Annotation> parse(File f) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance( );
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(f);
        return parse(doc);             
    }
    
    public ArrayList<Annotation> parse(String s) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance( );
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        InputStream is = new ByteArrayInputStream(s.getBytes());
        Document doc = docBuilder.parse(is);
        return parse(doc);             
    }
    
    private ArrayList<Annotation> parse(Document doc)  {
        doc.getDocumentElement().normalize();
        
        for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("Annotations".equalsIgnoreCase(n.getNodeName())) {
                return parseAnnotations(n);
            }
        }
        
        return null;
    }   

    private ArrayList<Annotation> parseAnnotations(Node n) {
        ArrayList<Annotation> annos = new ArrayList<>();
        for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
            if ("Annotation".equalsIgnoreCase(n.getNodeName())) {
                AnnotationXML_Parser p = new AnnotationXML_Parser();
                Annotation anno = p.parseAnnotationNode(n);
                annos.add(anno);
            }
        }
        return annos;
    }
    
}
